<template>
  <div>
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" />
  </div>
</template>

<script>
import { _local } from "@/utils/storage";

export default {
  data() {
    return {
      imUser: {},
      user: {},
    };
  },
  created() {
    const _this = this;
    if (JSON.stringify(_this.$global.ws) == "{}" && _local.get("imUser")) {
      _this.imUser = _local.get("imUser");
      _this.user = _local.get("user");
      _this.connectWebsocket();
    }
  },
  methods: {
    connectWebsocket() {
      const _this = this;
      if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!");
        const ws = new WebSocket("ws://47.92.222.96:7272");
        _this.$global.setWs(ws);
        ws.onopen = function (e) {
          console.log("开始连接");
          let login_data = {
            type: "login",
            client_name: _this.user.realname,
            room_id: "",
          };
          login_data = JSON.stringify(login_data);
          ws.send(login_data);
        };
        ws.onmessage = function (e) {
          console.log(JSON.stringify(e.data));
          let msg = JSON.parse(e.data);
          if (msg.type == "login") {
            fetch(`${_this.$imUrl}/im/bind`, {
              method: "POST",
              headers: {
                "Content-type":
                  "application/x-www-form-urlencoded; charset=UTF-8",
                token: _this.imUser.imToken,
              },
              body: `client_id=${msg.client_id}`,
            })
              .then((res) => res.json())
              .then((res) => {
                console.log("绑定", res);
                _this.$store.dispatch("im/setUnReadCount", {
                  unReadCount:
                    _local.get("unReadCount") || res.data.no_read_all,
                });
              });
          } else if (msg.type == "say") {
            _local.set("unReadCount", msg.no_read_all);
            _this.$store.dispatch("im/setUnReadCount", {
              unReadCount: msg.no_read_all,
            });
          }
        };
        ws.onclose = function (e) {
          console.log("连接中断");
          _this.connectWebsocket();
        };
      } else {
        console.log("您的浏览器不支持 WebSocket!");
      }
    },
  },
};
</script>

<style lang="less">
html,
body {
  height: 100%;
}
</style>
